// ignore_for_file: avoid_print

import 'dart:async';
import 'dart:io';

import 'package:flujs_qjs/binding/QJS.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as path;
import 'package:yaml/yaml.dart';

import 'fake_server.dart';

Future<void> testExecutable(FutureOr<void> Function() testMain) async {
  MockServer? server;
  try {
    final testEnv = path.join(Directory.current.path, 'test_env.yml');
    if (File(testEnv).existsSync()) {
      final yml = loadYaml(File(testEnv).readAsStringSync());
      print("[flutter_test_config] yaml = $yml");
      if (yml['QJS_DIR'] != null) {
        final qjsPath = yml['QJS_DIR']!;
        print('[flutter_test_config] QJS_DIR_PATH: $qjsPath');
        kQJSLibPath = qjsPath;
      }
    }
    server = MockServer();
    setUpAll(() async {
      try {
        await server!.start();
      } on Exception catch (e) {
        print('[⬆️] $e');
      }
    });
    await testMain();
  } catch (e, stackTrace) {
    print('[test] $e, $stackTrace');
  } finally {
    tearDownAll(() async {
      try {
        await server!.stop();
      } on Exception catch (e) {
        print('[⬆⬇️] $e');
      }
    });
  }
}
